<template>
  <div>
    <el-dialog
      v-if="!isMobile()"
      title="支付"
      v-model="dialogVisible"
      width="30%"
    >
      <div style="text-align: center">
        <div
          class="text-danger"
          style="font-size: 12px; margin-bottom: 10px"
        >
          * 使用微信扫码支付，支付中不要关闭弹窗，支付完成之后自动提交
        </div>
        <div>{{ payParams.goodsDesc }}</div>
        <h2 class="text-danger">￥{{ payParams.totalPrice }}</h2>
        <vue-qr
          v-if="payParams.codeUrl"
          :text="payParams.codeUrl"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 移动端/-->
    <van-popup
      v-if="isMobile()"
      v-model:show="dialogVisible"
      round
      position="bottom"
      :style="{ height: '30%' }"
    >
      <div style="margin: 20px">
        <div
          class="text-danger"
          style="font-size: 12px; margin-bottom: 10px"
        >
          * 点击后跳转至微信支付页面，支付完成后回到页面并自动提交
        </div>
        <h2 class="text-center">
          {{ payParams.goodsDesc }}
        </h2>
      </div>
      <van-submit-bar
        :price="payParams.totalPrice * 100"
        button-text="去支付"
        @submit="jumpMWebPay"
      />
    </van-popup>
  </div>
</template>

<script setup lang="ts" name="GoodsPay">
import { isMobile } from "@/views/formgen/utils";
import request from "@/utils/request";
import { isWxEnv } from "../hooks/wx";
import { Popup as VanPopup, SubmitBar as VanSubmitBar } from "vant";
import "vant/lib/popup/style";
import "vant/lib/submit-bar/style";
import "vant/lib/dialog/style";
import { getFormData, removeFormData, saveFormData } from "@/views/formgen/utils/db";
import loadWXJs from "@/views/formgen/utils/loadWxSdk";
import vueQr from "vue-qr/src/packages/vue-qr.vue";
import { onMounted, onUnmounted, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { useFormWx } from "@/views/form/write/hooks/useFormWxHook";
import { useUserForm } from "@/stores/userForm";
import { storeToRefs } from "pinia";

const emit = defineEmits(["paySuccess"]);

const dialogVisible = ref(false);
const randKey = ref("");
const payParams = ref<any>({
  codeUrl: "",
  goodsDesc: "",
  totalPrice: "",
  mwebUrl: ""
});
const transactionId = ref("");
let payStatusTimer: ReturnType<typeof setInterval> | null = null;
const tempFormModel = ref<any>({});
const formKey = ref("");

const route = useRoute();

const { isMiniAppWebview, redirectWxAuthorization } = useFormWx;

onMounted(() => {
  let source = route.query.source;
  randKey.value = route.query.randKey as string;
  formKey.value = route.params.key as string;
  tempFormModel.value = { formModel: getFormData(formKey.value) };

  // 支付完成回调页面
  if (source === "pay" && isMobile() && getFormData(formKey.value)) {
    ElMessageBox.confirm("您的微信支付是否已经完成？", "提示", {
      confirmButtonText: "完成",
      cancelButtonText: "放弃"
    })
      .then(() => {
        openIntervalQueryPayStatus();
      })
      .catch(() => {
        // on cancel
      });
  }
});

onUnmounted(() => {
  clearInterval(payStatusTimer!);
});

const userFormStore = useUserForm();

const { needGetWechatInfo, allFields } = storeToRefs(userFormStore);

watch(
  () => needGetWechatInfo.value,
  () => {
    if (!isWxEnv()) {
      return;
    }
    // 非小程序里面
    if (isMiniAppWebview.value) {
      return;
    }
    if (!route.query.code) {
      // 如果是微信里面支付要获取openid
      redirectWxAuthorization();
    }
  }
);

const openPay = (submitFormData: any, formKey: string) => {
  if (transactionId.value) {
    transactionId.value = "";
    return false;
  }
  // 随机5位数字 生成随机Id
  randKey.value = getOrderNoRandKey();
  const formModel = submitFormData.originalData;
  let payComs: any[] = [];
  Object.keys(formModel).forEach(key => {
    if (key.indexOf("goods_select") > -1) {
      // 找到组件 判断是否需要支付
      debugger;
      const filed = allFields.value.find(f => f.vModel == key);
      if (formModel[key] && Object.keys(formModel[key]).length !== 0 && filed?.isPayment != false) {
        // formModel[key] 是个对象 里面是商品的id和数量 {id001: 1, id002: 1} value加起来必须大于0
        // 累加对象的value  {id001: 1, id002: 1}
        let total = Object.keys(formModel[key]).reduce((total, gKey) => {
          return total + formModel[key][gKey];
        }, 0);
        if (total) {
          payComs.push({ key: key, value: formModel[key] });
        }
      }
    }
  });
  // 微信公众号的openId
  let openId = submitFormData.wxOpenId;
  if (payComs.length !== 0) {
    tempFormModel.value = submitFormData.originalData;
    tempFormModel.value["payRandKey"] = randKey.value;
    request
      .post("/form/ext/createGoodsPay", {
        formKey: formKey,
        randKey: randKey.value,
        isMobile: isMobile(),
        isMiniAppWebview: isMiniAppWebview.value,
        openId: openId,
        goodsList: payComs,
        extData: submitFormData
      })
      .then(res => {
        payParams.value = res.data;
        if (!isMobile()) {
          openIntervalQueryPayStatus();
        }
      })
      .catch(() => {
        dialogVisible.value = false;
      });
    dialogVisible.value = true;
    return true;
  }
  return false;
};

defineExpose({
  openPay
});

/**
 * 开启定时查询支付状态
 */
const openIntervalQueryPayStatus = () => {
  queryPayStatus();
  if (!payStatusTimer) {
    payStatusTimer = setInterval(queryPayStatus, 3000);
  }
};

const queryPayStatus = () => {
  request
    .get("/form/ext/queryPayStatus", {
      params: {
        randKey: randKey.value
      }
    })
    .then(res => {
      if (res.data) {
        transactionId.value = res.data;
        ElMessage.success({
          message: "支付成功",
          type: "success"
        });
        dialogVisible.value = false;
        removeFormData(formKey.value);
        clearInterval(payStatusTimer!);
        emit("paySuccess", res.data);
      }
    });
};

const jumpMWebPay = () => {
  if (isMiniAppWebview.value) {
    handleWxMiniAppPay();
    return;
  }
  if (isWxEnv()) {
    handleJsApiPay();
    return;
  }
  if (!payParams.value.mwebUrl) {
    return;
  }
  saveFormData(tempFormModel, formKey.value);
  let url = window.location.href.split("?")[0];
  let redirectUrl = `${url}?source=pay&randKey=${randKey.value}`;
  window.location.href = payParams.value.mwebUrl + "&redirect_url=" + encodeURIComponent(redirectUrl);
};

const handleWxMiniAppPay = () => {
  // 拉起小程序 把参数携带给他
  loadWXJs(wx => {
    let payDataStr = encodeURIComponent(JSON.stringify(payParams));
    const url = `/pages/form/pay/index?payDataStr=${payDataStr}`;
    wx.miniProgram.navigateTo({
      url: url
    });
  });
};

//@ts-nocheck
const handleJsApiPay = () => {
  //@ts-ignore
  if (typeof WeixinJSBridge == "undefined") {
    if (document.addEventListener) {
      document.addEventListener("WeixinJSBridgeReady", onBridgeReady, false);
      //@ts-ignore
    } else if (document.attachEvent) {
      //@ts-ignore
      document.attachEvent("WeixinJSBridgeReady", onBridgeReady);
      //@ts-ignore
      document.attachEvent("onWeixinJSBridgeReady", onBridgeReady);
    }
  } else {
    onBridgeReady();
  }
};

const onBridgeReady = () => {
  //@ts-ignore
  WeixinJSBridge.invoke(
    "getBrandWCPayRequest",
    {
      appId: payParams.value.appId,
      timeStamp: payParams.value.timeStamp,
      nonceStr: payParams.value.nonceStr,
      package: payParams.value.packageValue,
      signType: payParams.value.signType,
      paySign: payParams.value.paySign
    },
    function (res: any) {
      if (res.err_msg == "get_brand_wcpay_request:ok") {
        openIntervalQueryPayStatus();
      }
    }
  );
};

const getOrderNoRandKey = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = now.getMonth() + 1;
  const day = now.getDate();
  const hours = now.getHours();
  const minutes = now.getMinutes();
  const seconds = now.getSeconds();
  return `${year}${month}${day}${hours}${minutes}${seconds}` + Math.floor(Math.random() * 90000) + 10000;
};
</script>
